package com.ywyt.elasticsearch.service.impl;

import com.ywyt.elasticsearch.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class IndexServiceImpl implements IndexService {

    @Autowired
    private RestHighLevelClient client;


    public void createIndex(String index, String type, Settings.Builder settings, XContentBuilder mappingBuilder) throws IOException {

        //加上检查索引是否存在之后
        if (existsIndex(index)){
            log.warn("【创建索引】 索引已经存在 index = 【】",index);
        }else {
            //1.创建操作索引的request对象
            CreateIndexRequest request = new CreateIndexRequest(index)
                    .settings(settings)
                    .mapping(type,mappingBuilder);
            //2.执行创建索引操作
            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);

            //3.输出
            log.info("【创建索引】 index = {},type = {},response = {}",index,type,response);
        }
    }

    @Override
    public boolean existsIndex(String index) throws IOException {
        //1.创建查询索引request
        GetIndexRequest request = new GetIndexRequest();
        //2.设置索引名称
        request.indices(index);
        //3.通过client执行exists
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        return exists;
    }

    @Override
    public void deleteIndex(String index) throws IOException {
        //检查索引是否存在
        if (existsIndex(index)){
            //1.创建删除索引的request
            DeleteIndexRequest request = new DeleteIndexRequest();
            //2.指定索引名称
            request.indices(index);
            //3.删除
            AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
            //4.输出
            log.info("【删除索引】index = {},response = {}",index,response);
        }else {
            log.warn("【删除索引】索引不存在 index = {}",index);
        }
    }
}
